import { getTag, isObject, isObjectLike } from '@vimi/utils-tool'

export const isPlainObject = value => {
  if (!isObjectLike(value) || getTag(value) !== '[object Object]') {
    return false
  }

  if (Object.getPrototypeOf(value) === null) {
    return true
  }

  let proto = value
  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto)
  }
  return Object.getPrototypeOf(value) === proto
}

export const isEqual = (oldData, newData) => {
  if (oldData === newData) return true

  if (isObject(oldData) && isObject(newData)) {
    const keys = Object.keys(oldData)
    if (keys.length === Object.keys(newData).length) {
      for (const key of keys) {
        if (!isEqual(oldData[key], newData[key])) return false
      }
    }
  } else if (Array.isArray(oldData) && Array.isArray(newData)) {
    const { length } = oldData
    if (length === newData.length) {
      for (let i = 0; i < length; i++) {
        if (!isEqual(oldData[i], newData[i])) return false
      }
    }
  } else {
    return false
  }

  return true
}
